from rest_framework_simplejwt.serializers import TokenObtainSlidingSerializer
from rest_framework_simplejwt.views import TokenObtainSlidingView

from system.models import UserRole, Role


# 自定义令牌获取序列化器， 继承自TokenObtainSlidingSerializer
class CustomerTokenObtainSlidingPairSerializer(TokenObtainSlidingSerializer):
    # 设置用户名字段为username
    username_field = "username"
    # 获取token错误时返回的报错信息
    default_error_messages = {
        "no_active_account": "用户名或密码错误"
    }

    # 自定义token负载
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        user_role = UserRole.objects.get(user_id=user.id)
        role = Role.objects.get(id=user_role.role_id)

        # 添加个人信息
        token['role'] = role.role_type
        token['is_active'] = user.is_active
        return token

    # 重写validate的token验证方法
    def validate(self, attrs):
        # 调用父类的validate方法，存入登录用户数据
        data = super().validate(attrs)
        return data


# 自定义令牌获取视图，继承自TokenObtainSlidingView
class CustomTokenObtainSlidingPairView(TokenObtainSlidingView):
    # 设置序列化器类为自定义的CustomerTokenObtainSlidingPairSerializer
    serializer_class = CustomerTokenObtainSlidingPairSerializer
